import os
import uuid

from PIL import Image

# 配置路径和目标尺寸
input_dir = r"D:\pyimg\post\Philippines-women-20250522"
output_dir = r"D:\pyimg\post\Philippines-women-20250522-resize"
target_width = 1600
target_height = 1600

os.makedirs(output_dir, exist_ok=True)

def resize_image_keep_ratio(img, max_width, max_height):
    original_width, original_height = img.size

    # 计算缩放比例
    ratio = min(max_width / original_width, max_height / original_height)

    # 计算新的尺寸
    new_width = int(original_width * ratio)
    new_height = int(original_height * ratio)

    # 缩放图像
    return img.resize((new_width, new_height), Image.LANCZOS)

# 批量处理所有图片
for filename in os.listdir(input_dir):
    if filename.lower().endswith(('.jpg', '.jpeg', '.png')):
        src_path = os.path.join(input_dir, filename)
        save_name = f"{uuid.uuid4().hex}.jpg"
        dst_path = os.path.join(output_dir, save_name)
        try:
            img = Image.open(src_path).convert("RGB")
            resized_img = resize_image_keep_ratio(img, target_width, target_height)
            resized_img.save(dst_path)
            print(f"✅ 已缩放: {filename}")
        except Exception as e:
            print(f"❌ 处理失败: {filename} - {e}")
